﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PortUsedKill.Utils
{
    public class IpUtils
    {
        static readonly List<Regex> regices = new List<Regex>();

        private static void Init()
        {
            regices.Add(new Regex(""));
            regices.Add(new Regex("^10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])"
        + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])" + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"));
            // B类地址范围: 172.16.0.0---172.31.255.255
            regices.Add(new Regex("^172\\.(1[6789]|2[0-9]|3[01])\\" + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\"
                    + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"));
            // C类地址范围: 192.168.0.0---192.168.255.255
            regices.Add(new Regex("^192\\.168\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\"
                    + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"));
            regices.Add(new Regex("127.0.0.1"));
            regices.Add(new Regex("0.0.0.0"));
            regices.Add(new Regex("localhost"));
        }

        public static bool IpIsInner(string ip)
        {
            if (regices.Count == 0)
            {
                Init();
            }
            foreach (var item in regices)
            {
                if (item.IsMatch(ip))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
